﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Timers;
using System.Net;

#endregion


namespace ESF.Peer
{
	public class SocketState
	{
		#region Events

		public event Action<Socket> OnConnectionUnUsed;

		#endregion


		#region Members
		
		public Socket SocketHandler;
		
		public byte [] Buffer;
		
		public Stream Stream; 

		public bool IsEnd;

		private Timer _UnusedConnectionTimer;

		public int LastRequestTick;

		public IPEndPoint ClientIPEndPoint;
		
		#endregion


		#region Constructor

		public SocketState(int pReceiveWaitTimeoutMS = 5000, int pReadBufferLength = 1024)
		{
			IsEnd = false;

			Buffer = new byte [pReadBufferLength];

			Stream = new MemoryStream ();

			_UnusedConnectionTimer = new Timer (pReceiveWaitTimeoutMS);
			_UnusedConnectionTimer.Elapsed += _UnusedConnectionTimer_Elapsed;

			_UnusedConnectionTimer.Start ();

			LastRequestTick = Environment.TickCount;
		}

		#endregion


		#region Funciones

		public void StopTimer ()
		{
			_UnusedConnectionTimer.Stop ();
		}

		#endregion


		#region Timer Events

		private void _UnusedConnectionTimer_Elapsed(object sender, ElapsedEventArgs e)
		{
			// Si la diferencia entre el conteo actual menos el marcado del cliente es superior al de la espera se considera
			// que fue abandonada la conexión y se procede a cerrarla.
			if (Environment.TickCount - LastRequestTick > _UnusedConnectionTimer.Interval)
			{
				if (SocketHandler != null && SocketHandler.Connected)
				{
					if (OnConnectionUnUsed != null)
					{
						OnConnectionUnUsed (SocketHandler);
					}

					SocketHandler.Close ();

					StopTimer ();
				}
			}
		}

		#endregion
	}
}
